package com.webside.front.detail.controller;

import java.io.IOException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.stream.events.Comment;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.itextpdf.xmp.impl.Base64;
import com.mongodb.util.Util;
import com.webside.front.common.model.BSeries;
import com.webside.front.common.model.BVideo;
import com.webside.front.common.model.Bdictionary;
import com.webside.front.common.model.PBanner;
import com.webside.front.common.model.RComment;
import com.webside.front.detail.service.IDetailService;
import com.webside.front.detail.utils.EscapeUnescape;
import com.webside.front.detail.utils.HttpUtil;
import com.webside.front.detail.utils.TokenUtils;
import com.webside.front.listener.BaseData;
import com.webside.mongo.model.MongoRecord;
import com.webside.util.Common;
import com.webside.util.SensitivewordFilter;

import jodd.util.URLDecoder;

@Controller
@Scope("prototype")
@RequestMapping(value="/public/detail/")
public class DetailController {
	@Autowired
	private	IDetailService detailService;
	@Autowired
	private MongoTemplate mongoTemplate;
	
	public static String vcBasePath="http://vc.sh.vnet.cn:8080/auth_service";
	@RequestMapping(method = RequestMethod.GET, value = "/playVideo")
	public void playVideo(HttpServletRequest request, HttpServletResponse response) throws IOException{
		// TODO Auto-generated method stub
		String appId="abefe3a4-27e4-11e6-9089-047d7becc";
		String appKey="c3477aff-27e4-11e6-9089-047d7becc1fa";
		String encodeType=TokenUtils.ENCRY_TYPE_AES;
		String accessKey=TokenUtils.encodeRequest(appId, appKey, encodeType);
		
		String requestUrl=null;
		JSONObject returnJson=HttpUtil.executeHttpPost(vcBasePath+"/auth?accessKey="+accessKey+"&decodeType="+encodeType, null, null, null, null);
		try {
			String token=(String)returnJson.getString("token");
			String appInfo=TokenUtils.decodeResponse(token,encodeType);
			System.out.println(appInfo);
			String[] appInfoStrs=appInfo.split(TokenUtils.SPLIT_CHAR);
			
			String cdnToken=appInfoStrs[1];
			String resUrl=request.getParameter("res_url");
			String deResUrl=Base64.decode(resUrl);
			requestUrl=deResUrl+"&token="+cdnToken;
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		response.sendRedirect(requestUrl);
	}
	
	@RequestMapping("show.html")
	public String show(Model m,PBanner pbanner,@RequestParam("seriesId") Integer seriesId,@RequestParam("setNum") Integer setNum, Integer pageNo,String channel) throws Exception{
		m.addAttribute("baseImgPath",BaseData.img_base_path);
		m.addAttribute("channel", channel);
		System.out.println(channel+"+++++++++++");
		//简介
		BSeries bSeries= detailService.selectSeriesById(seriesId);
		/*List<Bdictionary> list=detailService.selectKeywords();*/
		m.addAttribute("bSeries",bSeries);
		/*String []keyarr=list.get(0).getName().split(",");
		m.addAttribute("bdictionaryKeywords_list",keyarr);
		System.out.println(list.size());*/
		//测试用hu
		
	
		 
		//剧集选择
		List<BVideo> bVideoList=detailService.selectVideoBySeriesId(bSeries.getId());
		m.addAttribute("bVideoList", bVideoList);
		System.out.println(bVideoList);
		BVideo bv=null;
		for(int i=0;i<bVideoList.size();i++){
			if( bVideoList.get(i).getSetNum()==setNum){
				bv=bVideoList.get(i);
				m.addAttribute("bVideo",bv);
				break;
			}	 
		}
		//播放次数
		Integer pCount=0;
		if(bv.getPlayCount()==null){
			pCount=1;
		}else{
			pCount=bv.getPlayCount()+1;
		}
		bv.setPlayCount(pCount);
		detailService.play(bv);
		//替换地址//
		String url=bv.getH720pUrl();
		url.replace("//", "\\\\");
		bv.setH720pUrl(url);
		
		//看过此片还喜欢
		BSeries conditionSeries=new BSeries();
		conditionSeries.setType(bSeries.getType());
		List<BSeries> mayLikeSeries=detailService.selectMayLike(bSeries);
		m.addAttribute("mayLikeSeriesList", mayLikeSeries);
		
		//排行推荐
		conditionSeries.setChannel(bSeries.getChannel());
		List<BSeries> mayChannelSeries=detailService.selectMayChannel(bSeries);
		m.addAttribute("mayChannelSeriesList", mayChannelSeries);
		
		
		
		//获得评论区分页参数
		int cPageSize;
		int c_Count=detailService.CommentCount(bv.getId());
		m.addAttribute("c_Count", c_Count);
		if(c_Count>7 ){
			cPageSize=c_Count/7;
			 if(c_Count%7==0){
					m.addAttribute("cPageSize",cPageSize);
				}else{
					m.addAttribute("cPageSize",cPageSize+1);
				}
		}else{
			cPageSize=0;
			m.addAttribute("cPageSize",cPageSize);
		}
		
		
		return Common.BACKGROUND_PATH + "/front/video";
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/addRecord.html")
	@ResponseBody
	public void getStatisticsRecord(MongoRecord mongoRecord,HttpServletRequest request) {
		System.out.println("进来了！========================");
		try {
			
				// 调用java自带的uuid生成唯一标示id
				UUID uuid = UUID.randomUUID();
				// 去掉不需要的字符
				String id = uuid.toString().replaceAll("\\-", "");
				// 为实体对象加入标示id
				mongoRecord.setId(id);
				mongoRecord.setIp(Common.toIpAddr(request));
				mongoTemplate.insert(mongoRecord,"play_records");


		} catch (Exception e) {
			e.printStackTrace();


		}
		// 返回标示符


	
		
	}
	//获得父级评论
	@RequestMapping("recomment.html")
	@ResponseBody
	public Object showComment(@RequestParam("videoId") Integer videoId,@RequestParam("pageNo") Integer pageNo,HttpSession session) throws Exception{
		System.out.println(pageNo);
		long beginTime = System.currentTimeMillis();
		List<RComment> rCommentList=detailService.selectRComment(videoId ,pageNo);
		session.setAttribute("commentCount",rCommentList.size());
 		SensitivewordFilter filter=new SensitivewordFilter();
		for (int i = 0; i < rCommentList.size()-1; i++) {
			String content= filter.replaceSensitiveWord(rCommentList.get(i).getContent(), 1, "*");
			rCommentList.get(i).setContent(content);
		}
		long endTime = System.currentTimeMillis();
		System.out.println("总共消耗时间为：" + (endTime - beginTime));
		JSONArray json1 = new JSONArray();
		json1.addAll(rCommentList);
		System.out.println(json1);
		if(json1.size()>0){
			return rCommentList;
		}
		String No_msg="";
		No_msg = "尚未评论";
		return json1;
	}
	//获得子级评论
	@RequestMapping("replyComment.html")
	@ResponseBody
	public Object showRComment(@RequestParam("videoId") Integer videoId,@RequestParam("pageNo") Integer pageNo,@RequestParam("parentId") Integer commentId,Model m) throws Exception{
		
		long beginTime = System.currentTimeMillis();
		List<RComment> rCommentList=detailService.selectReplyComment(videoId ,pageNo,commentId);
		 
		int r_Count=detailService.ReplyCount(commentId);
		int cPageSize_1=r_Count%7;
		if(r_Count%7==0){
			m.addAttribute("cPageSize_1",cPageSize_1);
		}else{
			m.addAttribute("cPageSize_1",cPageSize_1+1);
		}
		SensitivewordFilter filter=new SensitivewordFilter();
		for (int i = 0; i < rCommentList.size()-1; i++) {
			String content= filter.replaceSensitiveWord(rCommentList.get(i).getContent(), 1, "*");
			rCommentList.get(i).setContent(content);
		}
		long endTime = System.currentTimeMillis();
		System.out.println("总共消耗时间为：" + (endTime - beginTime));
		JSONArray json = new JSONArray();
		json.addAll(rCommentList);
		System.out.println(json);
		if(json.size()>0){
			return rCommentList;
		}
	     String	msg ="尚未回复评论";
	    /* JSONObject j = JSONObject.fromObject(msg);*/
		return msg;
	}
	//获得视频信息
	@RequestMapping("videoMsg.html")
	@ResponseBody
	public Object showVideoMsg(@RequestParam("videoId") Integer videoId){
		BVideo video = detailService.showVideoMsg(videoId);
		if(video!=null)
			return video;
		String videoMsg="视频信息缺失";
		return videoMsg;
	}
	//点赞
	@RequestMapping("likeCount.html")
	@ResponseBody
	public Object likeCount(@RequestParam("videoId") Integer videoId){
		Integer likeVideo = detailService.like(videoId);
		if(likeVideo!=null)
			return likeVideo;
		return 0;
	}
	//发表评论
	@RequestMapping("insertComment.html")
	@ResponseBody
	public Object insertComment(@RequestParam("videoId") Integer videoId,@RequestParam("parentId") Integer parentId,@RequestParam("content") String content,@RequestParam("childrenCount") String childrenCount){
		String c=URLDecoder.decode(content,"UTF-8");
		RComment comment=new RComment();
		comment.setVideoId(videoId);
		comment.setParentId(parentId);
		comment.setContent(c);
		if(childrenCount.equals("0") && childrenCount!=null){
			comment.setChildrenCount(1);
		}
		Date date=new Date();
		comment.setCreateTime(date);
		Object com = detailService.insertComment(comment);
		if(parentId!=0){
			detailService.addCount(comment);
		}
		
		if(comment!=null)
			return comment;
		return 0;
	}
	//资源集合
	/*@RequestMapping("EpisodeResouce.html")
	@ResponseBody
	public Object EpisodeResouce(@RequestParam("seriesId") Integer seriesId) throws Exception{
		List<RComment> rCommentList=detailService.selectVideo(seriesId );
		JSONArray json = new JSONArray();
		json.addAll(rCommentList);
		System.out.println(json);
		if(json.size()>0){
			return json;
		}
		String msg = "尚未回复评论";
		return msg;
	}
	*/
	//点赞
		@RequestMapping("test.html")
		public String test(){
			
			return  Common.BACKGROUND_PATH + "/front/test";
		}
}
